

package cn.liyao.web.controller;

import cn.hutool.json.JSONUtil;
import cn.liyao.tool.annotation.RequireToken;
import cn.liyao.tool.api.R;
import cn.liyao.web.constant.ConversationType;
import cn.liyao.web.holder.CurrentUserIdHolder;
import cn.liyao.web.model.Conversation;
import cn.liyao.web.model.Group;
import cn.liyao.web.model.Messages;
import cn.liyao.web.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@RestController

public class ConversationController {

    private final ConversationRepository conversationRepository;

    private final MessageRepository messageRepository;

    private final GroupRepository groupRepository;

    private final UserMessageRepository userMessageRepository;

    @Autowired
    public ConversationController(ConversationRepository conversationRepository, MessageRepository messageRepository, GroupRepository groupRepository, UserMessageRepository userMessageRepository) {
        this.conversationRepository = conversationRepository;
        this.messageRepository = messageRepository;
        this.groupRepository = groupRepository;
        this.userMessageRepository = userMessageRepository;
    }



    @GetMapping("/conversation/remove")
    @RequireToken()
    @Transactional()
    public R conversationSetRemark(String targetId, Boolean clearMessages) {
        String userId = CurrentUserIdHolder.getCurrentUser();
        conversationRepository.deleteByTargetIdAndUserId(targetId,userId);
        if(clearMessages == null ) clearMessages = false;
        if(clearMessages){
            conversationRepository.updateDeletedStatusByTargetId(targetId,userId);
        }

        return R.data("删除");
    }




    // 设置免打扰模式
    @GetMapping("/conversation/setDisturb")
    @RequireToken()
    public R conversationSetDisturb(String targetId) {
        String userId = CurrentUserIdHolder.getCurrentUser();
        Conversation conversation =  conversationRepository.findOneByUserIdAndTargetId(userId,targetId);
        if(conversation  == null ) R.fail("会话不存在");
        conversation.setDisturb(!conversation.getDisturb());
        conversationRepository.save(conversation);
        return R.data("设置成功");
    }



    @GetMapping("/conversation/top")
    @RequireToken()
    public R conversationSetRemark(String targetId) {
        String userId = CurrentUserIdHolder.getCurrentUser();
        Conversation conversation =  conversationRepository.findOneByUserIdAndTargetId(userId,targetId);
        if(conversation  == null ) R.fail("会话不存在");
        conversation.setTop(!conversation.getTop());
        conversationRepository.save(conversation);
        return R.data("设置成功");
    }





    @GetMapping("/conversation/setRemark")
    @RequireToken()
    public R conversationSetRemark(String name,String groupId) {
        String userId = CurrentUserIdHolder.getCurrentUser();
        Conversation conversation =  conversationRepository.findOneByUserIdAndTargetId(userId,groupId);
        if(conversation == null){
            return R.fail("会话不存在");
        }


        conversation.setRemark(name);
        conversationRepository.save(conversation);
        return R.success("修改成功");
    }



    @GetMapping("/conversation/list")
    @RequireToken()
    public R friendList() {
        String userId = CurrentUserIdHolder.getCurrentUser();
        List<Conversation> list =  conversationRepository.findAllByUserIdOrderByTimestampAsc(userId);
        for(Conversation conversation : list){
            if(conversation.getType() == ConversationType.Group.getValue()){
                Optional<Group> groupOptional =  groupRepository.findById(conversation.getTargetId());
                Slice<Messages> messagesSlice = messageRepository.findGroupMessageList(conversation.getTargetId(),System.currentTimeMillis(),conversation.getTargetId(), userId, PageRequest.of(0, 1));
                if(messagesSlice.getContent().size() > 0){
                   Messages messages =  messagesSlice.getContent().get(0);
                   conversation.setLastMessage(JSONUtil.toJsonStr(messages));
                   conversation.setTimestamp(messages.getTimestamp());
                   conversation.setUserName(groupOptional.get().getGroupName());
                   conversation.setPortrait(groupOptional.get().getPortrait());
                }
            }
        }
        return R.data(list);
    }

}